package com.example.chinesenation.Controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.chinesenation.ElasticSearch.ElasticSearchService;
import com.example.chinesenation.Entity.Article;
import com.example.chinesenation.Entity.Policy;
import com.example.chinesenation.Entity.SearchRecord;
import com.example.chinesenation.Exception.AuthenException;
import com.example.chinesenation.Redis.RedisService;
import com.example.chinesenation.Response.ResultType;
import com.example.chinesenation.Response.ServerResponse;
import com.example.chinesenation.Service.IArticleService;
import com.example.chinesenation.Service.ISearchRecordService;
import com.example.chinesenation.Utils.Audience;
import com.example.chinesenation.Utils.JwtTokenUtil;
import com.example.chinesenation.Utils.RecommendedTools;
import com.example.chinesenation.VO.MainPage.VOArticleList;
import com.example.chinesenation.VO.MainPage.VOPolicyList;
import com.example.chinesenation.VO.Search.VOArticleSearch;
import com.example.chinesenation.VO.Search.VOPolicySearch;
import com.example.chinesenation.VO.VOPolicy;
import io.swagger.annotations.ApiOperation;
import org.elasticsearch.client.RestHighLevelClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author sakuraFallingDown
 * @version 1.0
 * @date 2021/1/23 13:34
 */
@Controller
@ResponseBody
@RequestMapping("/search")
@CrossOrigin
public class SearchController {//用于搜索部分的接口

    private final Logger logger= LoggerFactory.getLogger(getClass());

    @Autowired
    private Audience audience;

    @Autowired
    private RedisService redisService;

    @Autowired
    private IArticleService articleService;

    @Autowired
    private ISearchRecordService searchRecordService;

    @Autowired
    private ElasticSearchService elasticSearchService;

    @Autowired
    private RecommendedTools recommendedTools;


    /**
     *
     * @param token 用户token
     * @param nation 筛选结果条件之一 筛选符合keyword的nation民族的数据
     * @param category 筛选结果条件之一 筛选符合keyword的分类的数据
     * @param keyword 搜索输入的keyword
     * @param start 筛选结果条件之一 筛选符合发布日期的开始日期
     * @param end 筛选结果条件之一 筛选符合发布日期的结束日期
     * @param orderByType 筛选结果条件之一 将最终结果进行排序 默认为分数匹配排序，1为按照发布时间，2为按照播放量
     * @param current 分页查询条件的目前所在页码
     * @param size 分页查询条件的目前所在页的大小
     * @return 返回符合条件的数据
     */
    @ApiOperation("搜索符合条件的民族文章信息接口")
    @PostMapping("/article")
    public ServerResponse<IPage<VOArticleSearch>> SearchArticle(@RequestHeader(value = "token",required = false) String token
            , @RequestParam(value = "nation",required = false) String nation
            , @RequestParam(value = "category",required = false)String category//是民族信息的哪个模块,例如民族旅游等等
            , @RequestParam(value = "keyword")String keyword
            , @RequestParam(required = false)Long start, @RequestParam(required = false)Long end
            , @RequestParam(required = false)Integer orderByType//1为
            , @RequestParam(value = "current") int current
            , @RequestParam(value = "size") int size){
        long time=System.currentTimeMillis();
        if(token!=null&&!token.equals("")){
            String uid= JwtTokenUtil.getUserId(token,audience);
            SearchRecord sr=new SearchRecord();
            sr.setKeyword(keyword);
            sr.setUid(uid);
            searchRecordService.save(sr);
        }
        try {
            Date startDate=null;
            Date endDate=null;
            if(start!=null){
                startDate=new Date(start);
            }
            if(end!=null){
                endDate=new Date(end);
            }
            if(orderByType==null){
                orderByType=0;
            }
            IPage<VOArticleSearch> iPage=elasticSearchService.searchArticle(
                    nation, category,keyword, startDate, endDate, orderByType, current, size);
            long time1=System.currentTimeMillis();
            logger.info(""+(time1-time));
            return ServerResponse.createSuccessResponse("查询成功",iPage);
        } catch (IOException e) {
            throw new AuthenException(ResultType.ElasticSearchERROR);
        }

    }

    /**
     *
     * @param token 用户token
     * @param nation 筛选结果条件之一 筛选符合keyword的nation民族的数据
     * @param keyword 搜索输入的keyword
     * @param start 筛选结果条件之一 筛选符合发布日期的开始日期
     * @param end 筛选结果条件之一 筛选符合发布日期的结束日期
     * @param orderByType 筛选结果条件之一 将最终结果进行排序 默认为分数匹配排序，1为按照发布时间，2为按照播放量
     * @param current 分页查询条件的目前所在页码
     * @param size 分页查询条件的目前所在页的大小
     * @return 返回符合条件的数据
     */
    @ApiOperation("搜索符合条件的政策信息接口")
    @PostMapping("/policy")
    public ServerResponse<IPage<VOPolicySearch>> SearchPolicy(@RequestHeader(value = "token",required = false) String token
            , @RequestParam(required = false)String nation
            , @RequestParam(value = "keyword") String keyword
            , @RequestParam(required = false)Long start, @RequestParam(required = false)Long end
            , @RequestParam(required = false)Integer orderByType
            , @RequestParam(value = "current") int current
            , @RequestParam(value = "size") int size){
        if(token!=null&&!token.equals("")){
            String uid= JwtTokenUtil.getUserId(token,audience);
            SearchRecord sr=new SearchRecord();
            sr.setKeyword(keyword);
            sr.setUid(uid);
            searchRecordService.save(sr);
        }
        try {
            Date startDate=null;
            Date endDate=null;
            if(start!=null){
                startDate=new Date(start);
            }
            if(end!=null){
                endDate=new Date(end);
            }
            if(orderByType==null){
                orderByType=0;
            }
            IPage<VOPolicySearch> iPage=elasticSearchService.searchPolicy(
                    nation, keyword, startDate, endDate, orderByType, current, size);
            return ServerResponse.createSuccessResponse("查询成功",iPage);
        } catch (IOException e) {
            throw new AuthenException(ResultType.ElasticSearchERROR);
        }

    }

    /**
     *
     * @return 返回筛选的热词
     */
    @ApiOperation("获取搜索页面热词接口")
    @PostMapping("/word")
    public ServerResponse<List<String>> getHotDoorSearch(){//获取热门搜索的词汇
        List<String> hotWord = null;
        if(redisService!=null){
            hotWord=(List<String>)redisService.get("search:hotword");
        }
        if(hotWord==null||hotWord.size()==0){
            //执行定时任务，更新redis缓存
            List<String> stringList=new ArrayList<>();
            stringList.add("中国");
            stringList.add("华中科技大学");
            stringList.add("寒假");
            stringList.add("软件");
            stringList.add("测试");
            hotWord=stringList;
            redisService.put("search:hotword",stringList);
        }
        return ServerResponse.createSuccessResponse("热门搜索更新完毕",hotWord);
    }

    /**
     *
     * @param token 用户token 必须有 此系统根据用户uid记录搜索记录
     *
     * @return 返回最近的十个搜索记录
     */
    @ApiOperation("获取搜索记录")
    @PostMapping("/searchrecord")
    public ServerResponse<List<String>> getSearchRecord(@RequestHeader("token")String token){//获取热门搜索的词汇
        List<String> searchRecord = null;
        String uid=JwtTokenUtil.getUserId(token,audience);
        QueryWrapper<SearchRecord> qw=new QueryWrapper();
        qw.eq("uid",uid);
        IPage<SearchRecord> iPage=new Page<>(1,10);
        List<SearchRecord> records = searchRecordService.page(iPage, qw).getRecords();
        searchRecord=records.stream().map(SearchRecord::getKeyword).collect(Collectors.toList());
        if(searchRecord.size()!=0) {
            return ServerResponse.createSuccessResponse("搜索记录查找成功", searchRecord);
        }else{
            return ServerResponse.createSuccessResponse("无搜索记录");
        }
    }

    /**
     *
     * @param id 文章id 根据文章的兴趣矩阵获取相关推荐
     * @param category 根据文章类别获取搜索的相近的推荐
     * @return
     */
    @ApiOperation("获取搜索的推荐文章内容")
    @PostMapping("/search/rearticle")
    public ServerResponse<List<VOArticleList>> getSearchRecommendedArticle(@RequestParam("id")String id,
                                                                    @RequestParam("category")String category){
        List<VOArticleList> articleLists = recommendedTools.recommendedSearchArticle(id, category);
        return ServerResponse.createSuccessResponse("推荐内容获取成功",articleLists);
    }

    /**
     *
     * @param id 政策id
     * @return
     */
    @ApiOperation("获取搜索的推荐政策内容")
    @PostMapping("/search/repolicy")
    public ServerResponse<List<VOPolicyList>> getSearchRecommendedPolicy(@RequestParam("id")String id
                                                                   ){//获取热门搜索的词汇
        List<VOPolicyList> policyLists = recommendedTools.recommendedSearchPolicy(id);
        return ServerResponse.createSuccessResponse("推荐内容获取成功",policyLists);
    }
}
